package foo.bar.wiki.web.action.comment;

import foo.bar.wiki.web.action.BaseActionBean;
import foo.bar.wiki.web.action.page.PageActionBean;
import foo.bar.wiki.web.extension.CommentTypeConverter;
import foo.bar.wiki.web.extension.PageTypeConverter;
import foo.bar.wiki.domain.Comment;
import foo.bar.wiki.domain.Page;
import foo.bar.wiki.services.WikiService;
import foo.bar.wiki.plugins.PluginException;
import net.sourceforge.stripes.validation.*;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.SimpleMessage;
import net.sourceforge.stripes.integration.spring.SpringBean;
import com.google.code.kaptcha.servlet.KaptchaServlet;
import com.google.code.kaptcha.Constants;

/**
 * @author tmjee
 * @version $Date$ $Id$
 */
public class AddCommentActionBean extends BaseActionBean {

    @Validate(converter = PageTypeConverter.class)
    private Page page;

    @Validate(converter = CommentTypeConverter.class)
    @ValidateNestedProperties({
        @Validate(field = "content", required = true, trim = true)        
    })
    private Comment comment;

    @Validate(required = true, trim = true)
    private String kaptcha;

    private WikiService wikiService;

    public Resolution save() throws PluginException {
        String pageId = page.getId();
        page.getComments().add(comment);
        comment.setPage(page);
        wikiService.saveComment(comment);
        getContext().getMessages().add(new SimpleMessage("Comment saved"));
        return new RedirectResolution(PageActionBean.class, "view").addParameter("page", pageId);
    }
    @ValidationMethod(on={"save"})
    public void validate_save(ValidationErrors validationErrors) {
        String _kaptchaFromSession = (String) getSessionAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (!_kaptchaFromSession.equals(kaptcha)) {
            validationErrors.add("kaptcha", new SimpleError("Kaptch mismatch"));        
        }
    }


    @SpringBean("wikiService")
    public void setWikiSevice(WikiService wikiService) {
        this.wikiService = wikiService;    
    }

    public Comment getComment() {
        return comment;
    }

    public void setComment(Comment comment) {
        this.comment = comment;
    }

    public Page getPage() {
        return page;
    }

    public void setPage(Page page) {
        this.page = page;
    }


    public String getKaptcha() {
        return kaptcha;
    }

    public void setKaptcha(String kaptcha) {
        this.kaptcha = kaptcha;
    }
}
